const app = getApp();
let topOpacity=0
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "快递预约", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,

    openid: '',
    shareTitle: "",
    shareImg: '',

    updataList: [], // 图片列表 
    sendImgArr: [], //提交数据时的图片
    name: '',
    tel: '',
    room: '',
    group: '', //组团
    remark: '', //备注
    is_register: 0,
    no_register_content: '',
    imgMax: 0,
    grouplist: [], //组团列表
    roomlist: [], //房号列表
    showMonment:true,
  },
  
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  closeMonment(){
    this.setData({
      showMonment:false
    })
  },
  //选择组团和房号
  bindMultiPickerChange(e) {
    var that = this;
    const {
      type,
      list
    } = e.currentTarget.dataset
    this.setData({
      [type]: this.data[list][e.detail.value].text
    })
    //type==group 选择的是组团
    if (type == 'group') {
      //清空可能选择好了的房号
      that.setData({
        room: ''
      });

      //后台请求此组团下的房号
      wx.request({
        url: that.data.baseUrl + 'getTeamDownRoom.php',
        method: 'POST',
        data: {
          'openid':that.data.openid,
          'team': that.data[list][e.detail.value].text
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.data.status == 1) {
            that.setData({
              roomlist: res.data.roomList
            })
          } else {
            app.showTip(res.data.msg);
          }
        },
        fail: function (res) {
          app.showTip('房号查询失败,请刷新页面重试');
        }
      });
    }
  },

  //获取备注
  partPro: function (e) {
    var value = e.detail.value.trim();
    this.setData({
      remark: value
    });
  },

  //从本地获取照片 
  getLocalityImg() {
    let that = this;
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFiles = res.tempFiles
        let answer = tempFiles.every(item => {
          return item.size <= parseInt(that.data.imgMax) * 1024 * 1024
        })
        if (answer) {
          const addpic = res.tempFiles.map(el => el.path)
          that.setData({
            updataList: [...that.data.updataList, ...addpic]
          })
        } else {
          app.showTip("上传图片不能大于" + that.data.imgMax + "M哦");
        }
      }
    })
  },

  //处理图片上传
  uploadImgHandle(row) {

    var that = this;
    wx.showLoading({
      title: '信息发布中...'
    });
    wx.uploadFile({
      url: that.data.baseUrl + "uploadsForumKd.php", //服务器接口
      method: 'POST',
      filePath: that.data.updataList[row],
      header: {
        'content-type': 'multipart/form-data'
      },
      name: 'file', //服务器定义的Key值
      formData: {},
      success: function (res) {
        //wx.hideLoading();
        console.log(res.data);
        if (res.data) {
          var sendImgArr = that.data.sendImgArr;
          sendImgArr.push(res.data);
          that.setData({
            sendImgArr: sendImgArr
          });

          if (that.data.updataList.length == that.data.sendImgArr.length) {
            //调用最终上传数据
            wx.hideLoading();

            that.sendData();
          } else {
            that.uploadImgHandle(row + 1);
          }
        } else {
          app.showTip('服务器保存图片失败,请刷新页面重试');
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
      }
    });
  },

  //提交最终数据
  sendData() {
    var that = this;

    wx.showLoading({
      title: '信息提交中...'
    });

    wx.request({
      url: that.data.baseUrl + 'addKdBm.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'name': that.data.name,
        'tel': that.data.tel,
        'team': that.data.group,
        'room_number': that.data.room,
        'remark': that.data.remark,
        'imgArr': JSON.stringify(that.data.sendImgArr)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          app.showTip(res.data['msg']);
          setTimeout(function () {
            wx.navigateTo({
              url: '/pages/expressReservation/appointmentSuccess/index?id=' + res.data.id
            });
          }, 1500);
        } else {
          app.showTip(res.data['msg']);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });

  },

  //删除照片功能与预览照片功能 
  deleteImg(e) {
    let img_arr = this.data.updataList;
    let index = e.currentTarget.dataset.index;
    img_arr.splice(index, 1);
    this.setData({
      updataList: this.data.updataList
    })
  },
  //预览图片
  previewImg(e) {
    let index = e.currentTarget.dataset.index;
    let img_arr = this.data.updataList;
    wx.previewImage({
      current: img_arr[index],
      urls: img_arr
    })
  },

  //点击预约
  cj() {
    var that = this;
    //判断是否注册
    if (this.data.is_register == '0') {
      wx.showModal({
        title: '温馨提示',
        content: that.data.tipsContent,
        complete: (res) => {
          if (res.confirm) {
            //跳转注册界面
            wx.setStorageSync('loginHeaderUrl', '/pages/expressReservation/infor/index');
            wx.setStorageSync('loginHeaderType', 'redirectTo')
            if (res.confirm) {
              //跳转注册界面
              wx.redirectTo({
                url: '/pages/login/index'
              })
            }
          }
        }
      })
      return;
    }

    if (this.data.name === '') {
      this.toastHand('请输入姓名')
    } else if (this.data.tel === '') {
      this.toastHand('请输入电话')
    } else if (this.data.tel.length !== 11) {
      this.toastHand('请输入正确的电话')
    } else if (this.data.group === '') {
      this.toastHand('请选择组团')
    } else if (this.data.room === '') {
      this.toastHand('请选择房号')
    } else if (!this.data.updataList.length && this.data.remark == '') {
      this.toastHand('照片和备注至少要任选其一填写哦')
    } else {
      //判断是否上传了图片
      if (that.data.updataList.length > 0) {
        //上传了 先上传照片
        that.uploadImgHandle(0);
      } else {
        //未上传 直接提交数据
        that.sendData();
      }
    }
  },



  toastHand(e) {
    wx.showToast({
      title: e,
      icon: 'none'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    // openid='oZYOb4jQ1cdq3ZdTqRcQX4r_BI5Y'
    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');
    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getKdPageInfo(res.data.openid);

                //调用分享
                that.getShareInfo();
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //调用分享
      that.getShareInfo();

      //获取本页数据
      that.getKdPageInfo(openid);
    }
  },

  //获取本页数据
  getKdPageInfo(openid) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getKdPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //赋值页面数据
          that.setData({
            info: res.data.info,
            is_register: res.data.is_register,
            no_register_content: res.data.no_register_content,
            imgMax: res.data.imgMax,
            grouplist: res.data.teamList
          });
          var info = res.data.info;
          if (info.name != '') {
            that.setData({
              name: info.name
            });
          }
          if (info.tel != '') {
            that.setData({
              tel: info.tel
            });
          }

        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {
        pid:10
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/lifeService/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})